package lookas.screen;

import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;

import lookas.GoogleGeoposMidlet;

public abstract class SimpleScreen implements Screen, CommandListener {
	protected Screen parent;
	protected Form form;
	private Vector cmds;

	protected abstract void init();

	public SimpleScreen(Screen s) {
		this.parent = s;
		cmds = new Vector();
		init();
		Command back = new Command("Back", Command.ITEM, 10);
		addCommand(back, new Runnable() {
			public void run() {
				Display.getDisplay(parent.getMidlet()).setCurrent(
						parent.getForm());
			}
		});
		Command exit = new Command("Exit", Command.ITEM, 11);
		addCommand(exit, new Runnable() {
			public void run() {
				parent.getMidlet().close();
			}
		});
		form.setCommandListener(this);
		Display.getDisplay(parent.getMidlet()).setCurrent(form);
	}

	public GoogleGeoposMidlet getMidlet() {
		return parent.getMidlet();
	}

	public Displayable getForm() {
		return form;
	}

	public void commandAction(Command cmd, Displayable arg1) {
		Enumeration els = cmds.elements();
		while (els.hasMoreElements()) {
			Cmd c = (Cmd) els.nextElement();
			if (c.cmd == cmd) {
				c.run.run();
				return;
			}
		}
	}

	public void addCommand(Command cmd, Runnable run) {
		form.addCommand(cmd);
		Cmd c = new Cmd(cmd, run);
		cmds.addElement(c);
	}

	class Cmd {
		Command cmd;
		Runnable run;

		public Cmd(Command cmd, Runnable run) {
			this.cmd = cmd;
			this.run = run;
		}
	}
}
